from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Game(models.Model):
    name = models.CharField(max_length=200, primary_key=True)
 
    def __unicode__(self):
        return self.name

class GameField(models.Model):
    types = (
             ('team', 'team'),
             ('player', 'player'),
             ('yes/no', 'yes/no'),
    )
    game = models.ForeignKey(Game)
    " E.g. who win, count of resources of specified player, upper bound of count kills, etc."
    description = models.CharField(max_length=1000)
    " Percentage of users money that he will get if win "
    winnings = models.IntegerField(default=0)
    " Three type: independent of team and players, dependent on team, dependent on player "
    type = models.CharField(max_length=100, choices=types)
    
    def __unicode__(self):
        # TODO it is hell! FIXME!!!
        if self.game_id != 1:
            return "%s (%s)" % (self.game, self.description)
        
class Team(models.Model):
    game = models.ForeignKey(Game)
    name = models.CharField(max_length=200)
    rating = models.IntegerField(default=0)
    
    def __unicode__(self):
        return "%s (%s)" % (self.name, self.game.name)

class Tournament(models.Model):
    game = models.ForeignKey(Game)
    team = models.ManyToManyField(Team)
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=1000)
    # FIXME return name + description, because name may be not unique
    def __unicode__(self):
        return self.name

class Player(models.Model):
    team = models.ForeignKey(Team)
    name = models.CharField(max_length=200)
    rating = models.IntegerField(default=0)
    
class TournamentResult(models.Model):
    tournament = models.ForeignKey(Tournament)
    bet = models.ForeignKey(GameField)
    result = models.CharField(max_length=1000)

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    gold = models.IntegerField(default=100)
    
    def __str__(self):  
        return "%s's profile" % self.user
    
class UserBet(models.Model):
    user = models.ForeignKey(User)
    bet = models.ForeignKey(GameField)
    tournament = models.ForeignKey(Tournament)
    value = models.CharField(max_length=1000)
    gold = models.IntegerField(default=0)
    active = models.IntegerField(default=1)

def create_user_profile(sender, instance, created, **kwargs):  
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)  

post_save.connect(create_user_profile, sender=User) 
